package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.BusinessException;
import com.mall.common.ResultCode;
import com.mall.model.Cart;
import com.mall.model.Product;
import com.mall.repository.CartMapper;
import com.mall.repository.ProductMapper;
import com.mall.service.CartService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    
    private final ProductMapper productMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addToCart(Cart cart) {
        // 查询商品信息
        Product product = productMapper.selectById(cart.getProductId());
        if (product == null) {
            throw new BusinessException(ResultCode.PRODUCT_NOT_EXIST);
        }
        // 检查库存
        if (product.getStock() < cart.getQuantity()) {
            throw new BusinessException(ResultCode.PRODUCT_STOCK_INSUFFICIENT);
        }
        
        // 查询购物车是否已存在该商品
        Cart existCart = getOne(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, cart.getUserId())
                .eq(Cart::getProductId, cart.getProductId()));
        
        if (existCart != null) {
            // 更新数量
            existCart.setQuantity(existCart.getQuantity() + cart.getQuantity());
            updateById(existCart);
        } else {
            // 设置商品信息
            // 保存购物车
            save(cart);
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateQuantity(Long id, Integer quantity) {
        // 查询购物车商品
        Cart cart = getById(id);
        if (cart == null) {
            throw new BusinessException(ResultCode.CART_ITEM_NOT_EXIST);
        }
        
        // 查询商品信息
        Product product = productMapper.selectById(cart.getProductId());
        if (product == null) {
            throw new BusinessException(ResultCode.PRODUCT_NOT_EXIST);
        }
        // 检查库存
        if (product.getStock() < quantity) {
            throw new BusinessException(ResultCode.PRODUCT_STOCK_INSUFFICIENT);
        }
        
        // 更新数量
        cart.setQuantity(quantity);
        updateById(cart);
    }
    
    @Override
    public void deleteFromCart(Long id) {
        // 查询购物车商品
        if (!exists(id)) {
            throw new BusinessException(ResultCode.CART_ITEM_NOT_EXIST);
        }
        // 删除购物车商品
        removeById(id);
    }
    
    @Override
    public void clearCart(Long userId) {
        // 删除用户所有购物车商品
        remove(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId));
    }
    
    @Override
    public List<Cart> getUserCart(Long userId) {
        // 查询用户购物车列表
        return list(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId)
                .orderByDesc(Cart::getCreateTime));
    }
    
    private boolean exists(Long id) {
        return count(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getId, id)) > 0;
    }
} 